package com.module_live.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.herewhite.sdk.Room;
import com.herewhite.sdk.WhiteBroadView;
import com.herewhite.sdk.domain.AkkoEvent;
import com.herewhite.sdk.domain.AnimationMode;
import com.herewhite.sdk.domain.Appliance;
import com.herewhite.sdk.domain.EventEntry;
import com.herewhite.sdk.domain.EventListener;
import com.herewhite.sdk.domain.PptPage;
import com.herewhite.sdk.domain.Scene;
import com.herewhite.sdk.domain.ViewMode;
import com.lib.app.ARouterPathUtils;
import com.lib.app.ActivityUtils;
import com.lib.app.CodeUtil;
import com.lib.app.FragmentTag;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.fragment_deal.FragmentCustomUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.status_bar.QMUI.QMUIStatusBarHelper;
import com.lib.fastkit.utils.status_bar.StatusBarUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.views.circle_image.niv.NiceImageView;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.OneButtonDialog;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverManager;
import com.lib.utls.glide.GlideConfig;
import com.lib.utls.picture_select.PhotoUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.module_live.R;
import com.module_live.bean.CloseRoomBean;
import com.module_live.bean.CourseDeleteBean;
import com.module_live.bean.CourseUploadBean;
import com.module_live.bean.DaYiConectTimeRecordBean;
import com.module_live.bean.OtoControlBean;
import com.module_live.bean.RoomChatBean;
import com.module_live.bean.WhiteBoradBean;
import com.module_live.fragment.CharControlFragment;
import com.module_live.fragment.ChatWhiteBroadFragment;
import com.module_live.utils.WhiteBoardUtils;
import com.qiniu.droid.rtc.QNErrorCode;
import com.qiniu.droid.rtc.QNRTCEngine;
import com.qiniu.droid.rtc.QNRTCEngineEventListener;
import com.qiniu.droid.rtc.QNRTCSetting;
import com.qiniu.droid.rtc.QNRoomState;
import com.qiniu.droid.rtc.QNSourceType;
import com.qiniu.droid.rtc.QNStatisticsReport;
import com.qiniu.droid.rtc.QNTrackInfo;
import com.qiniu.droid.rtc.QNTrackKind;
import com.qiniu.droid.rtc.model.QNAudioDevice;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.Nullable;

@Route(path = ARouterPathUtils.Tablet_Live_LiveRoomActivity)
public class DaYiConnectRoomActivity extends BaseRoomActivity implements
        QNRTCEngineEventListener {

    //房间Token
    @Autowired(name = "roomToken")
    String roomToken;
    //当前房间的老师
    @Autowired(name = "teacherPhone")
    String teacherPhone;
    //房间名称
    @Autowired(name = "roomName")
    String roomName;
    //当前用户的手机号
    @Autowired(name = "userPhone")
    String userPhone;
    //白板UUID
    @Autowired(name = "uuid")
    String uuid;
    //白板Token
    @Autowired(name = "whitetoken")
    String whitetoken;

    @Autowired(name = "teacherId")
    int teacherId;
    @Autowired(name = "studentId")
    int studentId;
    @Autowired(name = "studentHeadUrl")
    String studentHeadUrl;
    @Autowired(name = "studentName")
    String studentName;
    @Autowired(name = "teacherHeadUrl")
    String teacherHeadUrl;
    @Autowired(name = "teacherName")
    String teacherName;

    @Autowired(name = "course_id")
    String course_id;

    //身份表示(1老师 0学生)
    private String identity = "";
    private String userToken = "";
    private String userIcon = "";
    private String userName = "";

    //直播引擎
    private static QNRTCEngine mEngine;
    //本地的音频流
    private QNTrackInfo localAudioTrack;

    private WhiteBroadView whiteBroadView;

    //用来判断学生是否取消进入直播间   0-正常下课,1-学生未进入直播间
    public int isStundentJoinRoom = 0;
    public int roomnum = 1;

    //用于判断老师是否点击了下课按钮
    private boolean isTeacherClose = false;

    //用于判断老师是否异常退出
    private boolean teacherUnknowExit = false;

    CoachAIStudyDialog dialog;

    //用户装载ppt地址的容器
    List<String> pptUrlList = new ArrayList<>();
    int index = 0;

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.arg1 == 1) {

                if (pptUrlList.size() > 0)
                    pptUrlList.clear();

                if (whiteBoardRoom != null && roomControlFragment != null) {

                    LogUtil.e("当前白板数量为：" + whiteBoardRoom.getScenes().length);
                    for (int i = 0; i < whiteBoardRoom.getScenes().length; i++) {
                        if (whiteBoardRoom.getScenes().length > 0 && i < whiteBoardRoom.getScenes().length) {
                            Scene scene = whiteBoardRoom.getScenes()[i];
                            LogUtil.e("白板名称" + scene.getName());
                            if (scene != null) {
                                if (scene.getPpt() != null) {
                                    pptUrlList.add(scene.getPpt().getSrc());
                                } else {
                                    pptUrlList.add("");
                                }

                            }
                        }
                    }
                    roomControlFragment.updateBroadList(pptUrlList);
                }
            }
        }
    };

    //用于记录直播间时长
    long baseTimer = SystemClock.elapsedRealtime();

    Handler myhandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (0 == baseTimer) {
                baseTimer = SystemClock.elapsedRealtime();
            }

            int time = (int) ((SystemClock.elapsedRealtime() - baseTimer) / 1000);
            String hh = new DecimalFormat("00").format(time / 3600);
            String mm = new DecimalFormat("00").format(time / 60);
            String ss = new DecimalFormat("00").format(time % 60);
            if (null != tvTime) {
                tvTime.setText(hh + ":" + mm + ":" + ss);
            }
            Message message = Message.obtain();
            message.what = 0x0;
            sendMessageDelayed(message, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * 初始换页面配置
         */
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        StatusBarUtil.statusBarTintColor(this, getResources().getColor(R.color.transparent));
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_chatroom);

        ARouter.getInstance().inject(this);

        initBaseData();

        roomControlBean = new OtoControlBean();
        whiteBoradBean = new WhiteBoradBean();

        /**
         * 通过横竖屏来获取不同的控件
         * 横竖屏是两套页面
         */
        findView();

        /**
         * 控制
         */
        initRoomControlFragment();

        /**
         * 直播
         */
        initEngine();


        /**
         * 白板
         */
        initWhiteBorad();
        initWitheBoardFragment();

        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        dialog = CoachAIStudyDialog.getInstance();

    }

    @Override
    protected void onResume() {
        super.onResume();

        //发送计时消息
        myhandler.sendMessageDelayed(Message.obtain(myhandler, 1), 1000);

    }

    FrameLayout frWhiteboard;
    NiceImageView ivUser;
    TextView tvName;
    TextView tvTime;
    LinearLayout linDismis;
    FrameLayout frControl;

    /**
     * 获取控件ID
     */
    private void findView() {

        frWhiteboard = findViewById(R.id.fr_whiteboard);
        frControl = findViewById(R.id.fr_control);

        ivUser = findViewById(R.id.iv_user);
        tvName = findViewById(R.id.tv_name);
        tvTime = findViewById(R.id.tv_time);
        linDismis = findViewById(R.id.lin_dismis);

        //当前身份为老师，左上角显示学生头像及名称
        if ("1".equals(identity)) {

            if (StringUtil.isNotEmpty(studentHeadUrl, true)) {
                Glide.with(this)
                        .load(studentHeadUrl)
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }
            tvName.setText(studentName);

        } else if ("2".equals(identity)) { //当前身份为学生，左上角显示老师头像及名称
            if (StringUtil.isNotEmpty(teacherHeadUrl, true)) {
                Glide.with(this)
                        .load(teacherHeadUrl)
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }
            tvName.setText(teacherName);
        }
    }

    private void initBaseData() {

        /**
         * 初始化页面数据
         */
        roomToken = getIntent().getStringExtra("roomToken");
        roomName = getIntent().getStringExtra("roomName");
        teacherPhone = getIntent().getStringExtra("teacherPhone");
        userPhone = getIntent().getStringExtra("userPhone");
        whitetoken = getIntent().getStringExtra("whitetoken");
        uuid = getIntent().getStringExtra("uuid");

        //進入直播間的老师和学生的Id，用于统计直播间时间
        studentId = getIntent().getIntExtra("studentId", -1);
        teacherId = getIntent().getIntExtra("teacherId", -1);

        //老师--学生之间的信息
        teacherHeadUrl = getIntent().getStringExtra("teacherHeadUrl");
        teacherName = getIntent().getStringExtra("teacherName");
        studentHeadUrl = getIntent().getStringExtra("studentHeadUrl");
        studentName = getIntent().getStringExtra("studentName");

        course_id = getIntent().getStringExtra("course_id");

        identity = SharedPreferenceManager.getInstance(this).getUserCache().getUserIdentity();
        userToken = SharedPreferenceManager.getInstance(this).getUserCache().getUserToken();
        userIcon = SharedPreferenceManager.getInstance(this).getUserCache().getUserHeadUrl();
        userName = SharedPreferenceManager.getInstance(this).getUserCache().getUserName();

    }

    //控制页面
    public static CharControlFragment roomControlFragment;
    //白板
    public static ChatWhiteBroadFragment whiteBoardFragment;

    private void initRoomControlFragment() {

        roomControlFragment = new CharControlFragment();
        roomControlFragment.setRoomControlFragmentListener(controlFragmentListener);
        FragmentCustomUtils.setFragment(this, R.id.fr_control, roomControlFragment, FragmentTag.ChatControlFragment);
    }

    private void initWitheBoardFragment() {

        whiteBoardFragment = new ChatWhiteBroadFragment(whiteBroadView, whiteBoardRoom);
        whiteBoardFragment.setWhiteBoardFragmentListener(whiteBoardFragmentListener);

        FragmentCustomUtils.setFragment(this, R.id.fr_whiteboard, whiteBoardFragment, FragmentTag.ChatWhiteFragment);
    }

    /**
     *==============================================================================================
     * ==========================================================================直播相关
     * =============================================================================================
     */

    /**
     * 初始化直播
     */

    private QNRTCSetting setting = new QNRTCSetting();

    private void initEngine() {

        /**
         * 设置是否默认音频路由为扬声器
         *
         * @param defaultAudioRouteToSpeakerphone 若为 true，则默认为扬声器，若为 false，则为听筒
         */
        setting.setDefaultAudioRouteToSpeakerphone(true);

        mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, this);

        //音频流
        localAudioTrack = mEngine.createTrackInfoBuilder()
                .setSourceType(QNSourceType.AUDIO)
                .setMaster(true)
                .create();

        LogUtil.e("当前房间的roomToken为:" + roomToken);

        mEngine.joinRoom(roomToken);

    }


    /**
     *==============================================================================================
     * ==========================================================================白板
     * =============================================================================================
     */

    /**
     * 初始化白板状态
     */
    private void initWhiteBoradStae() {

        //显示白板
        frWhiteboard.setVisibility(View.VISIBLE);

        if (whiteBoardRoom != null) {
            //开启白板操作权限
            whiteBoardRoom.disableDeviceInputs(false);
            if ("1".equals(identity)) {
                whiteBoardRoom.setViewMode(ViewMode.Broadcaster);
            } else if ("2".equals(identity)) {
                whiteBoardRoom.setViewMode(ViewMode.Follower);
            }
            //设置白板摄像头固定，无法缩放图片
            whiteBoardRoom.disableCameraTransform(true);
            //设置白板图铺满屏幕
            whiteBoardRoom.scalePptToFit(AnimationMode.Continuous);
            whiteBoardFragment.refreshRoom();
        }

    }

    WhiteBoardUtils whiteBoardUtils;

    private static Room whiteBoardRoom;

    //白板页面状态管理
    public static WhiteBoradBean whiteBoradBean;
    //控制页面的状态管理
    public static OtoControlBean roomControlBean;

    /**
     * 初始化白板
     */
    private void initWhiteBorad() {

        whiteBroadView = new WhiteBroadView(this);
        whiteBoardUtils = WhiteBoardUtils.getInstance().joinToRoom(
                this, whiteBroadView, uuid, whitetoken, userPhone);

        whiteBoardUtils.setWhiteBoardListener(new WhiteBoardUtils.WhiteBoardListener() {
            @Override
            public void onJoinRoomSucess(Room room) {
                if (whiteBoardFragment != null) {
                    whiteBoardRoom = room;
                    whiteBoardFragment.setRoom(room);

                    //初始化画笔颜色
                    whiteBoardFragment.setBoradTool(Appliance.PENCIL);

                    showLog("room回调");

                    if (roomControlFragment == null) {
                        roomControlFragment = new CharControlFragment();
                    }

                    //初始化白板状态
                    initWhiteBoradStae();

                    //添加白板监听事件
                    addEvevtListener();

                    //通知老师学生进入直播间
                    if ("2".equals(identity))
                        sengWhiteEventMsg("5", "已进入直播间！");
                }
            }

            @Override//当房间状态改变时，刷新白板和用户列表
            public void onRoomStateChange() {

            }

            @Override//尝试重新加入房间
            public void onRetryJoinin() {
                if (whiteBroadView == null) {
                    whiteBroadView = new WhiteBroadView(DaYiConnectRoomActivity.this);
                }
                whiteBoardUtils = WhiteBoardUtils.getInstance().joinToRoom(DaYiConnectRoomActivity.this,
                        whiteBroadView, uuid, whitetoken, userPhone);

            }

            @Override//当老师下课之后，主动让学生退出直播间
            public void onKickedOutRoom(String reason) {

                LogUtil.e("onKickedOut" + reason);
                isTeacherClose = true;
                //判断是否是老师点击了下课，如果是，则老师不显示提示框
                if (isTeacherClose && "1".equals(identity)) {
                    return;
                } else {
                    OneButtonDialog.getInstance()
                            .setTitle("温馨提示")
                            .setContent("本次课程已结束，请退出直播间")
                            .setSureListener(new OneButtonDialog.SurelListener() {
                                @Override
                                public void onSure() {
                                    requestLeaveRoom();
                                }
                            }).show(getSupportFragmentManager());
                }
            }
        });
    }

    public static final String EVENT_NAME = "WHITEBROADCOMMANDDAYIMESSAGE";

    /**
     * 添加自定义事件，用于获取用户列表以及显示聊天消息
     */
    private void addEvevtListener() {

        whiteBoardRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
            @Override
            public void onEvent(EventEntry eventEntry) {
                if (eventEntry != null) {
                    if (EVENT_NAME.equals(eventEntry.getEventName())) {
                        String json = null;
                        //因为白板SDK问题，eventEntry.getPayload()可能会出现String或者Object，分别判断一下
                        if (eventEntry.getPayload() instanceof String) {
                            LogUtil.e("eventEntry.getPayload()类型为String");
                            json = (String) eventEntry.getPayload();
                        } else if (eventEntry.getPayload() instanceof Object) {
                            LogUtil.e("eventEntry.getPayload()类型为Object");
                            json = MGson.newGson().toJson(eventEntry.getPayload());
                        }
                        LogUtil.e("白板自定义收到的json为：" + json);
                        RoomChatBean chatBean = MGson.newGson().fromJson(json, RoomChatBean.class);
                        //学生举手，给老师消息提示
                        if ("4".equals(chatBean.getType())) {
                            if ("1".equals(identity)) {

                                showStudentOperateDialog(chatBean.getUserName(), chatBean.getMessage());
                            }
                        } else if ("5".equals(chatBean.getType())) {//通知老师学生进入直播间
                            if ("1".equals(identity)) {

                                showStudentOperateDialog(chatBean.getUserName(), chatBean.getMessage());
                            }
                        } else if ("6".equals(chatBean.getType())) {//通知老师学生进入直播间
                            if ("2".equals(identity)) {

//                                LogUtil.e("============老师下课啦");
//                                OneButtonDialog.getInstance()
//                                        .setTitle("温馨提示")
//                                        .setContent("本次课程已结束，请退出直播间")
//                                        .setSureListener(new OneButtonDialog.SurelListener() {
//                                            @Override
//                                            public void onSure() {
//                                                requestLeaveRoom();
//                                            }
//                                        }).show(getSupportFragmentManager());
                            }
                        }
                    }
                }
            }
        });

    }


    /**
     * 弹出工具框
     *
     * @param studentName 申请的学员姓名
     * @param operateType 申请的类型  -- 举手，进入直播间等
     */
    public void showStudentOperateDialog(String studentName, String operateType) {

        if (StringUtil.isNotEmpty(studentName, true)) {

            dialog.setTitle("温馨提示")
                    .setContent("学生" + studentName + operateType)
                    .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                        @Override
                        public void onCancel() {

                        }
                    })
                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
                        @Override
                        public void onSure() {

                        }
                    }).show(getSupportFragmentManager());

        }
    }

    /**
     * 当按下屏幕返回键时，调用退出接口
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //如果老师点击下课或者因其他原因退出直播间，学生可以点击返回退出直播间
            if (isTeacherClose || isTeacherClose) {
                requestLeaveRoom();
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();

        //true代表当前正在后台运行，暂不退出直播间
        if (ActivityUtils.isBackground(this)) {

            LogUtil.e("app已经不在后台运行，退出直播间");
            //false代表程序已经被杀死，需要退出直播间
            requestLeaveRoom();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        clearConfigInfo();
    }

    /**
     * 离开房间
     */
    //老师每次下课扣除1个课时
    private void leaveRoom() {
        dialog.setTitle("温馨提示")
                .setContent("确认要退出直播间么？")
                .setSureListener(new CoachAIStudyDialog.SurelListener() {
                    @Override
                    public void onSure() {
                        //发送本次连线数据到后台
                        sendConnectTimeToService();
                    }
                }).show(getSupportFragmentManager());

    }

    /**
     * 请求离开房间
     */
    int leaveRequestNum = 0;

    private void requestLeaveRoom() {

        LogUtil.e("请求requestLeaveRoom()接口时，leaveRequestNum的值为：" + leaveRequestNum);

        HttpUtils.with(DaYiConnectRoomActivity.this)
                .addParam("requestType", "LIVE_DROPOTU_ROOM")
                .addParam("room_name", roomName)
                .addParam("token", userToken)
                .addParam("consume_class", "1")
                .execute(new HttpNormalCallBack<CloseRoomBean>() {
                    @Override
                    public void onSuccess(CloseRoomBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            LogUtil.e("退出直播间成功");

                            //更新新版问答老师显示首页
                            ObserverManager.getInstance().notifyObserver("updateNewShareCare");

                            clearConfigInfo();

                        } else {

                            //当返回码不等于200时，再次请求退出接口
                            ++leaveRequestNum;
                            LogUtil.e("请求出错fail时，leaveRequestNum的值为：" + leaveRequestNum);
                            //请求三次依然出现错误时，直接强制退出直播间
                            if (leaveRequestNum <= 3) {
                                requestLeaveRoom();
                            } else if (leaveRequestNum > 3) {
                                clearConfigInfo();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                        //当请求出现错误时，再次请求退出接口
                        ++leaveRequestNum;
                        LogUtil.e("请求出错onError时，leaveRequestNum的值为：" + leaveRequestNum);
                        //请求三次依然出现错误时，直接强制退出直播间
                        if (leaveRequestNum <= 3) {
                            requestLeaveRoom();
                        } else if (leaveRequestNum > 3) {
                            clearConfigInfo();
                        }
                    }
                });
    }


    public void clearConfigInfo() {

        if (myhandler != null) {
            myhandler.removeCallbacksAndMessages(null);
        }
        //清空七牛数据
        if (mEngine != null) {
            mEngine.leaveRoom();
            mEngine.destroy();
            mEngine = null;
        }

        //清空白板数据
        if (whiteBoardRoom != null) {
            whiteBoardRoom.removeMagixEventListener(WhiteBoardUtils.EVENT_NAME);
            whiteBoardRoom.disconnect();
        }

        //清空fragment和观察者模式
        removeFragment();

        finish();

    }

    private void removeFragment() {
        FragmentCustomUtils.removeFragment(this, FragmentTag.ChatControlFragment);
        FragmentCustomUtils.removeFragment(this, FragmentTag.ChatWhiteFragment);
    }

    /**
     * 获取白板房间
     *
     * @return
     */

    public static Room getwhiteBoardRoom() {

        return whiteBoardRoom;
    }

    @Override
    public void onRoomStateChanged(QNRoomState qnRoomState) {

        LogUtil.e("onRoomStateChanged");

        switch (qnRoomState) {
            case RECONNECTING:
                //重新连接中
                showToast("重新连接中");
                break;
            case CONNECTED:
                //连接成功
                toTeacherPublishTrack();
                showLog("连接直播房间成功");
                break;
            case RECONNECTED:
                //重新连接成功
                break;
            case CONNECTING:
                //连接中
                showToast("连接中");
                break;
        }

    }

    /**
     * 推送流
     */
    private void toTeacherPublishTrack() {

        mEngine.publishTracks(Arrays.asList(localAudioTrack));

    }

    @Override
    public void onRemoteUserJoined(String s, String s1) {

        LogUtil.e("直播-onRemoteUserJoined用户加入:" + s + "消息:" + s1);

        if (StringUtil.isNotEmpty(s, true)) {
            roomnum += 1;
        }
        updateWhiteList();

    }

    @Override
    public void onRemoteUserLeft(String s) {
        LogUtil.e("直播-onRemoteUserLeft用户离开:" + s);

        LogUtil.e("s的值为:" + s + "，teacherPhone的值为：" + teacherPhone);
        if (s.equals(teacherPhone)) {

            if (isTeacherClose) {
                Toast.makeText(DaYiConnectRoomActivity.this,
                        "老师已经退出，直播间即将关闭！", Toast.LENGTH_LONG).show();

                requestLeaveRoom();
            } else {
                sendConnectTimeToService();
            }
        }
        updateWhiteList();
    }


    @Override
    public void onLocalPublished(List<QNTrackInfo> list) {
        LogUtil.e("直播-onLocalPublished数据大小:" + list.size());

    }

    @Override
    public void onRemotePublished(String s, List<QNTrackInfo> list) {

        for (int i = 0; i < list.size(); i++) {
            QNTrackInfo myTrackInfo = list.get(i);
            if (QNTrackKind.VIDEO.equals(myTrackInfo.getTrackKind())) {

//                qnSurfaceView.setVisibility(View.VISIBLE);
//                mEngine.setRenderWindow(myTrackInfo, qnSurfaceView);
            }
        }
    }

    @Override
    public void onRemoteUnpublished(String s, List<QNTrackInfo> list) {

        for (int i = 0; i < list.size(); i++) {
            QNTrackInfo myTrackInfo = list.get(i);
            if (QNTrackKind.VIDEO.equals(myTrackInfo.getTrackKind())) {

//                qnSurfaceView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onRemoteUserMuted(String remoteUserId, List<QNTrackInfo> list) {

        LogUtil.e("直播-onRemoteUserMuted人数:" + list.size());

//        updateWhiteList();
    }

    @Override
    public void onSubscribed(String s, List<QNTrackInfo> list) {

        LogUtil.e("直播-onSubscribed人数:" + list.size());
    }

    @Override
    public void onKickedOut(String s) {
        LogUtil.e("onKickedOut");
    }

    @Override
    public void onStatisticsUpdated(QNStatisticsReport qnStatisticsReport) {
        LogUtil.e("直播-onStatisticsUpdated");
    }

    @Override
    public void onAudioRouteChanged(QNAudioDevice qnAudioDevice) {
        LogUtil.e("直播-onAudioRouteChanged");
    }

    @Override
    public void onCreateMergeJobSuccess(String s) {
        LogUtil.e("直播-onCreateMergeJobSuccess");
    }

    @Override
    public void onError(int errorCode, String description) {
        LogUtil.e("onError");

        //10022-用户已存在，一般可能是该用户已在其他设备进入房间。 // 10004-重连时roomToken 错误
        if (10022 == errorCode || 10004 == errorCode) {

            OneButtonDialog.getInstance()
                    .setTitle("温馨提示")
                    .setContent("直播间正在准备中，请退出后重新进入")
                    .setSureListener(new OneButtonDialog.SurelListener() {
                        @Override
                        public void onSure() {
//                            requestLeaveRoom();
                        }
                    }).show(getSupportFragmentManager());

        } else if (errorCode == QNErrorCode.ERROR_TOKEN_INVALID
                || errorCode == QNErrorCode.ERROR_TOKEN_ERROR
                || errorCode == QNErrorCode.ERROR_TOKEN_EXPIRED) {
            showToast("roomToken 错误，请重新加入房间");
        } else if (errorCode == QNErrorCode.ERROR_AUTH_FAIL
                || errorCode == QNErrorCode.ERROR_RECONNECT_TOKEN_ERROR) {

            showToast("roomToken 错误");

        } else if (errorCode == QNErrorCode.ERROR_PUBLISH_FAIL) {

            showToast("发布失败，请重新加入房间发布");
        } else {
            showToast("errorCode:" + errorCode + " description:" + description);
        }
    }

    private int pageIndex = 0;

    /**
     * 将本地图片转换成bitmap对象
     *
     * @param pathUrl
     * @return
     */
    public static Bitmap getImageWidth(String pathUrl) {

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pathUrl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(fis);
        return bitmap;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoUtil.WHITE_BORAD_IMAGE:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> boardSelectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia boardMedia = boardSelectList.get(0);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    if (boardMedia.isCompressed()) {
                        String compressPath = boardMedia.getCompressPath();

                        if (whiteBoardFragment != null) {
                            whiteBoardFragment.upLoadImage(getImageWidth(compressPath), course_id, "image", compressPath, pageIndex);
                        }
                    }
                    break;
                case PhotoUtil.WhiteBroadPPt_Image:

                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> pptSelectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia pptMedia = pptSelectList.get(0);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (pptMedia.isCompressed()) {
                        String compressPath = pptMedia.getCompressPath();
                        if (whiteBoardFragment != null) {
                            whiteBoardFragment.upLoadImage(getImageWidth(compressPath), course_id, "pptimage", compressPath, pageIndex);
                        }
                    }
                    break;
            }

        } else if (resultCode == RESULT_CANCELED) {

            FragmentCustomUtils.removeFragment(DaYiConnectRoomActivity.this, FragmentTag.ChatWhiteFragment);
            initWitheBoardFragment();

        }
    }

    final String SCENE_DIR = "/ppt";
    public ChatWhiteBroadFragment.WhiteBoardFragmentListener whiteBoardFragmentListener = new ChatWhiteBroadFragment.WhiteBoardFragmentListener() {

        @Override
        public void uploadImgSuccess() {

            //因为选择图片、ppt均需要横竖屏切换，fragment会重新走一遍生命周期，此处便需要先清除，再进行添加
            FragmentCustomUtils.removeFragment(DaYiConnectRoomActivity.this, FragmentTag.ChatWhiteFragment);
            initWitheBoardFragment();
        }

        @Override
        public void uploadPPTImgSuccess(CourseUploadBean courseUploadBean) {

            FragmentCustomUtils.removeFragment(DaYiConnectRoomActivity.this, FragmentTag.OtoWhiteBroadFragment);
            initWitheBoardFragment();

            Double width = Double.valueOf(DisplayUtil.getScreenWidth(DaYiConnectRoomActivity.this));
            Double height = Double.valueOf(DisplayUtil.getScreenHeight(DaYiConnectRoomActivity.this));

            LogUtil.e("图片地址为：" + courseUploadBean.getObj().getCourseware_hash());
            PptPage pptPage = new PptPage(courseUploadBean.getObj().getCourseware_hash(), width, height);
            Scene scene = new Scene("ppt" + courseUploadBean.getObj().getCourseware_id(), pptPage);
            LogUtil.e("@@@@@@@@@@@@@@@@@@@@" + scene.getName());
            whiteBoardRoom.putScenes(SCENE_DIR, new Scene[]{scene}, 0);
            LogUtil.e("PPT的路径：" + SCENE_DIR + "/ppt" + courseUploadBean.getObj().getCourseware_id());
            whiteBoardRoom.setScenePath(SCENE_DIR + "/ppt" + courseUploadBean.getObj().getCourseware_id());
            whiteBoardRoom.scalePptToFit(AnimationMode.Continuous);

            updateWhiteList();
        }
    };


    /**
     * 获取当前白板数量 和用户信息
     */
    public void updateWhiteList() {

        Message message = new Message();
        message.arg1 = 1;
        handler.sendMessage(message);

    }

    public CharControlFragment.RoomControlFragmentListener controlFragmentListener = new CharControlFragment.RoomControlFragmentListener() {
        @Override
        public void onLeaveRoom() {
            //如果是老师点击了下课按钮，就需要进行赋值，方便后面判断
            if ("1".equals(identity)) {
                isTeacherClose = true;
            }
            //发送本次连线数据到后台
            leaveRoom();
        }

        @Override
        public void onWhiteBroadSelected(int position) {//显示选中的ppt

            LogUtil.e("在白板列表中选中的位置为：" + position);
            pageIndex = position;
            if (whiteBoardRoom != null) {
                Scene[] sceneArr = whiteBoardRoom.getScenes();
                if (sceneArr.length > 0) {
                    Scene scene = sceneArr[position];
                    if (scene != null && StringUtil.isNotEmpty(scene.getName(), true)) {
                        showLog("当前页码:" + scene.getName());
                        whiteBoardRoom.setScenePath(SCENE_DIR + "/" + scene.getName());
                    }
                }
            }
        }

        @Override//展示白板列表
        public void onWhiteBroadClick() {
            updateWhiteList();
        }

        @Override
        public void onAddNoneWhiteBroad() {//添加一个空白的白板
            long pageName = TimeUtils.getNowTimestamp();
            Scene scene = new Scene("ppt" + pageName);
            whiteBoardRoom.putScenes(SCENE_DIR, new Scene[]{scene}, 0);
            whiteBoardRoom.setScenePath(SCENE_DIR + "/ppt" + pageName);
            whiteBoardRoom.scalePptToFit(AnimationMode.Continuous);
            updateWhiteList();
        }

        @Override
        public void onMoveToNextBroad() {//移动到下一页白板
            ++pageIndex;
            if (whiteBoardRoom != null) {
                Scene[] scenesArr = whiteBoardRoom.getScenes();
                if (pageIndex == scenesArr.length) {
                    showToast("当前已经是最后一页");
                } else {
                    if (scenesArr.length > 0 && pageIndex < scenesArr.length) {
                        Scene scene = scenesArr[pageIndex];
                        if (scene != null && StringUtil.isNotEmpty(scene.getName(), true)) {
                            whiteBoardRoom.setScenePath(SCENE_DIR + "/" + scene.getName());
                            showLog("当前页码:" + "/" + scene.getName());
                        }
                    }
                }
            }
        }

        @Override
        public void onDeletePPTImage(int position) {//删除某一页PPT

            if (whiteBoardRoom != null) {
                Scene[] scenesArr = whiteBoardRoom.getScenes();
                if (scenesArr.length > 0) {
                    Scene scene = scenesArr[position];
                    if (scene != null && StringUtil.isNotEmpty(scene.getName(), true)) {
                        showLog("当前页码:" + "/" + scene.getName());
                        whiteBoardRoom.removeScenes("/ppt/" + scene.getName());
                    }
                    LogUtil.e("当前删除课件Id为：" + scene.getName().split("t")[1]);
                    //将删除的课件上传到service
                    uploadDeleteToService(scene.getName().split("t")[1]);
                }
            }
        }

        @Override
        public void onStudentPuyHand() {

            sengWhiteEventMsg("4", "老师请讲慢一点，我没听懂！");
        }
    };

    /**
     * 通过白板自定义事件发送消息和用户进入提示
     *
     * @param type
     * @param message
     */
    public void sengWhiteEventMsg(String type, String message) {
        RoomChatBean chatBean = new RoomChatBean();
        chatBean.setMessageId(TimeUtils.getNowTimestamp() + "");
        chatBean.setMessage(message);
        chatBean.setType(type);
        chatBean.setUserIcon(userIcon);
        chatBean.setUserName(userName);
        chatBean.setIdentity(identity);

        String json = MGson.newGson().toJson(chatBean);
        AkkoEvent akkoEvent = new AkkoEvent(EVENT_NAME, json);
        LogUtil.e("用户发送的数据为：" + json);

        if (whiteBoardRoom != null) {
            whiteBoardRoom.dispatchMagixEvent(akkoEvent);
        }
    }

    private void sendConnectTimeToService() {

        //如果人数大于1，为学生已进入
        LogUtil.e("直播间人数为：" + roomnum);
        if (roomnum == 1) {//学生未进入直播间
            isStundentJoinRoom = 1;
        } else if (roomnum > 1) {
            //如果房间两个人，并且老师点击了下课，则正常退出，否则老师异常退出
            LogUtil.e("直播间老师是否异常退出：" + !isTeacherClose);
            if (isTeacherClose) {
                isStundentJoinRoom = 0;
            } else {
                //老师异常退出
                isStundentJoinRoom = 2;
            }
        }
        String time = tvTime.getText().toString().trim();
        LogUtil.e("直播时长time的值为：" + time);
        if (StringUtil.isNotEmpty(time, true)) {
            HttpUtils.with(this)
                    .addParam("requestType", "LIVE_BROADCAST_COMPLETED")
                    .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                    .addParam("student_id", studentId)//	记录id
                    .addParam("teacher_id", teacherId)
                    .addParam("live_time", time)//直播时长
                    .addParam("is_normal", isStundentJoinRoom)
                    .execute(new HttpNormalCallBack<DaYiConectTimeRecordBean>() {
                        @Override
                        public void onSuccess(DaYiConectTimeRecordBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {
                                LogUtil.e("直播时长修改成功");

                                //退出直播间
                                requestLeaveRoom();
                            }
                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }
    }

    /**
     * 将删除的信息发送到服务器
     *
     * @param courseware_id
     */
    private void uploadDeleteToService(String courseware_id) {
        HttpUtils.with(this)
                .addParam("requestType", "QUESTIONS_COURS_COURSEWARE_DELETE")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("courseware_id", courseware_id)
                .execute(new HttpNormalCallBack<CourseDeleteBean>() {
                    @Override
                    public void onSuccess(CourseDeleteBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            showToast(result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


}
